<?php

declare(strict_types=1);
/**
 * 作者：薛原
 * 功能：管理后台文章控制器
 * 时间：2025/10/17
 */
namespace App\Controller\Admin;

use App\Service\ArticleService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Contract\RequestInterface;

use Hyperf\HttpServer\Annotation\Middleware;

#[Controller(prefix: "/admin/articles")]
//token认证中间件,管理员身份认证中间件
#[Middleware(\App\Middleware\AdminRoleCheckMiddleware::class)]

class ArticlesController extends AbstractController
{

    #[Inject]
    private ArticleService $articleService;

    /**
     * 管理员文章列表接口
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("")]
    public function index(RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $params = $this->parseParams($request);
        $size = isset($request->$params["size"])?$request->$params["size"] : 20;
        $page = isset($request->$params["page"])?$request->$params["page"] : 1;
        try{
            $ret = $this->articleService->getAllArticleList($size, $page);

        }catch (\App\Exception\BusinessException $e){
            return $this->fail(40002,"请求失败",["errors"=>$e->getMessage()]);
        }
        return $this->success($ret,"请求成功");
    }

    /**
     * 管理员执行审核接口
     * @param RequestInterface $request
     * @param $id
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PutMapping("{id}/review")]
    public function review(RequestInterface $request, $id): array|\Psr\Http\Message\ResponseInterface
    {
        $params = $this->parseParams($request);
        //1为通过，0未回到草稿状态
        $deal = isset($params['deal'])?$params['deal']:1;
        $article_id = $id;
        try{
            if($deal){
                $ret = $this->articleService->pulishArticle($article_id);
            }else{
                $ret = $this->articleService->refuseArticle($article_id);
            }
        }catch (\App\Exception\BusinessException $e){
            return $this->fail(40002,"请求失败",["errors"=>$e->getMessage()]);
        }
        return $this->success(null,"操作成功");
    }

    /**
     * 管理员获取文章详情
     * @param RequestInterface $request
     * @param $id
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[getMapping("{id}")]
    public function detail(RequestInterface $request, $id): array|\Psr\Http\Message\ResponseInterface
    {
        $article_id = $id;
        try {
            $ret = $this->articleService->getArticleById($article_id);
        } catch (\App\Exception\BusinessException $e) {
            return $this->fail(40002, "请求失败", ["errors" => $e->getMessage()]);
        }
        return $this->success($ret, "success");
    }
}
